import router from "@/router";
import axios from "axios";
import { ElMessage } from "element-plus";
import { useTokenStore } from "@/stores/token";

const request = axios.create({
  baseURL: "/api", // 注意！！ 这里是全局统一加上了 '/api' 前缀，也就是说所有接口都会加上'/api'前缀在，页面里面写接口的时候就不要加 '/api'了，否则会出现2个'/api'，类似 '/api/api/user'这样的报错，切记！！！
  timeout: 30000,
  headers: {
    // 设置后端需要的传参类型
    "X-Requested-With": "XMLHttpRequest",
  },
});

request.interceptors.request.use(
  (config) => {
    config.headers["Content-Type"] = "application/json;charset=utf-8";
    const useToken = useTokenStore();
    let token = useToken.token;
    if (token) {
      config.headers["token"] = token; // 设置请求头
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// request 拦截器
request.interceptors.response.use(
  function (response) {
    const res = response.data;
    const code = res.code;
    if (code !== 200) {
      ElMessage({
        showClose: true,
        message: res.message,
        type: "error",
      });
    }
    if (code === 403) {
      ElMessage({
        showClose: true,
        message: res.message,
        type: "error",
      });
      router.push("/");
    }
    return res;
  },
  function (error) {
    console.log(error);
    let code = error.code;
    let message = error.message;
    //网络超时异常处理
    if (
      code === "ECONNABORTED" ||
      message === "timeout of 10000ms exceeded" ||
      message.includes("timeout")
    ) {
      ElMessage({
        showClose: true,
        message: "请求超时，执行失败！",
        type: "error",
      });
    }
    return Promise.resolve(error);
  }
);

export default request;
